// 示例首页
var util = require('../../utils/util.js')
//index.js
const demoImgUrls = require('../../utils/data.js').demoImgUrls

var timestamp = +new Date()

//获取应用实例
const app = getApp()

Page({
  
  onShareAppMessage: function (res) {
    if (res.from === 'button') {
      return {
        title: '我的心里话都在这里',
        path: '/pages/index-old/index?shareIndex=' + this.data.current,
        success: function (res) {
          // 转发成功
        },
        fail: function (res) {
          // 转发失败
        }
      }
      this.hideMenu()
      // 来自页面内转发按钮
      console.log(res.target)
    }
    return {
      title: '我的心里话都在这里',
      path: '/pages/index/index',
      success: function (res) {
        // 转发成功
      },
      fail: function (res) {
        // 转发失败
      }
    }
  },
  check(){
    var that = this 
    // /v1/wechat/filterText?text = xxx
    var submitData = util.initData
    submitData.data = {
      app: 'NOTES'
    }
    wx.request({
      //填写自己的鉴权服务器地址
      url: 'https://m.youyinian.cn/v1/common/isAudit',
      method: 'POST',
      data: submitData,
      success: function (res) {
        console.log(res)
        var isPass = res.data.data.isPass
        that.setData({
          isPass : true
        })
        
      }
    })   
  },
  data: {

    isOpen : false , 
    msg: '' ,


    isPass: false ,
    // app.globalData 全局变量
    prefix: app.globalData.oldPrefix,

    motto: 'Hello World',
    userInfo: {},
    hasUserInfo: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    
    // swipe
    imgUrls: [
    ],
    indicatorDots: false,
    autoplay: false,
    circular : true ,
    interval: 5000,
    duration: 1000,
    current: 0,
    isScroll : false , // 用户触摸时用于隐藏 两侧 图片，形成视觉差

    // actionsheet 
    isShowMenu: false ,
    qrcodeUrl: '' // 合成图底部 二维码 下载到本地 
  },
  
  onLoad: function (options) {
    this.check()

    if (options.shareIndex){
      this.setData({
        current: options.shareIndex
      })
    }

    var that = this 
    wx.downloadFile({
      url: app.globalData.oldPrefix + '/create/qrcode.png?abc=' + timestamp ,
      success: function (res) {
        console.log('download success2');
        console.log(res.tempFilePath)
        that.setData({
          qrcodeUrl: res.tempFilePath
        })
      }
    })

    // 示例图片
    this.setData({
      imgUrls: demoImgUrls
    })
    if (app.globalData.userInfo) {
      this.setData({
        userInfo: app.globalData.userInfo,
        hasUserInfo: true
      })
    } else if (this.data.canIUse){
      // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
      // 所以此处加入 callback 以防止这种情况
      app.userInfoReadyCallback = res => {
        this.setData({
          userInfo: res.userInfo,
          hasUserInfo: true
        })
      }
    } else {
      // 在没有 open-type=getUserInfo 版本的兼容处理
      wx.getUserInfo({
        success: res => {
          app.globalData.userInfo = res.userInfo
          this.setData({
            userInfo: res.userInfo,
            hasUserInfo: true
          })
        }
      })
    }
  },
  // tip 提示bar 关闭时回调
  close(){
    console.log('关闭')
  },
  getUserInfo: function(e) {
    console.log(e)
    app.globalData.userInfo = e.detail.userInfo
    this.setData({
      userInfo: e.detail.userInfo,
      hasUserInfo: true
    })
  },
  // swiper 
  swiperChange(e) {
    this.setData({
      current: e.detail.current
    })
  },
  swiperTouchStart(){
    console.log('start')
    this.setData({
      isScroll : true ,
    })
  },
  swiperTouchEnd() {
    console.log('end')
    var that = this
    setTimeout(function(){
      that.setData({
        isScroll: false,
      })
    },400) 
  },
  // actionsheet 
 showMenu(){
   this.setData({ isShowMenu : true })
 },
 hideMenu(){
   this.setData({ isShowMenu: false })
 },
 //将canvas转换为图片保存到本地，然后将图片路径传给image图片的src
 createNewImg: function (url) {
  //  wx.showToast({
  //    title: '正在保存...',
  //    icon: 'loading',
  //    duration: 1500
  //  });
   var that = this
   var context = wx.createCanvasContext('mycanvas');
   var path = url

   var pixelRatio = 2
   
   //将模板图片绘制到canvas,在开发工具中drawImage()函数有问题，不显示图片
   //不知道是什么原因，手机环境能正常显示
   wx.getSystemInfo({
     success: function (res) {

      //  var longH = 890/750  * res.windowWidth
      //  var shortH = 210/750 * res.windowWidth

      //   //var longRadio = 891 / 1100
      //   //var shortRadio = 210 / 1100
      //   var widthRadio = 630 / 750
      //  //console.log(longRadio, shortRadio)
      //  //var th = res.windowHeight * longRadio
      //  //var bh = res.windowHeight * shortRadio
      //  var wh = res.windowWidth * widthRadio
      //  context.drawImage(path, 0, 0, wh, longH);
      //  context.drawImage(that.data.qrcodeUrl, 0, longH, wh, shortH)



       var defaultWidth = 750
       var defaultHeight = 1210

       var longH = 890 / 750 * res.windowWidth
       var shortH =  122 / 750 * res.windowWidth
       // 底板
       var screenWidth = res.windowWidth
       var screenHeight = res.windowHeight

       var screenRadio = (1210 -110) / 750
       var boardHeight = screenWidth * screenRadio
       // 底板相对 屏幕居中 
       var outerOffsetTop = (screenHeight - boardHeight )/2
       context.setFillStyle('white')


       context.fillRect(0, outerOffsetTop, res.windowWidth, boardHeight)
       // 计算居中参数
       var widthRadio = 630 / 750
       var wh = res.windowWidth * widthRadio
       console.log('wh', wh)
       var centerOffsetLeft = (screenWidth - wh) / 2
       var offsetTop = (res.windowHeight * (107 / 2)) / defaultHeight + outerOffsetTop

       context.drawImage(path, centerOffsetLeft, offsetTop, wh, longH);

       // 白色底版高度 - 模版图 y方向偏移量 - 模版图 高度 - 二维码高度 = ¥  return （¥ ／2）
       var qrcodeOffsetTop = (boardHeight - offsetTop + outerOffsetTop - longH - shortH) / 2 + longH + offsetTop 

       //  本地qrcode
      //  context.drawImage('../../images/qrcode.png', centerOffsetLeft, longH + offsetTop, wh, shortH)
        // cdn 的
       context.drawImage(that.data.qrcodeUrl, centerOffsetLeft, qrcodeOffsetTop, wh, shortH) 



       //context.draw(true);
       //context.draw();
       //绘制图片
       context.draw();
       //将生成好的图片保存到本地，需要延迟一会，绘制期间耗时
       setTimeout(function () {
         wx.canvasToTempFilePath({
           canvasId: 'mycanvas',
           success: function (res) {
             var tempFilePath = res.tempFilePath;
             console.log('测试', tempFilePath)
             wx.hideToast()
             console.log(tempFilePath);
             wx.saveImageToPhotosAlbum({
               filePath: tempFilePath,
               success: function () {
                 //that.hideMenu()    
                 wx.showModal({
                   title: '小提示',
                   showCancel: false,
                   content: '图片已经保存至相册，快秀到朋友圈给大家看把!',
                   duration: 1000
                 })
               },
               fail: function () {

               }
             })
           },
           fail: function (res) {
             console.log(11111, res);
           }
         });
       }, 200);


     }
   })

 },
  // 保存在相册
  saveAsAtAlumb(){
    var that = this
    wx.showToast({
      title: '正在保存...',
      icon: 'loading',
      duration : 1000
    })
    wx.downloadFile({
      url: demoImgUrls[this.data.current],
      success: function (res) {
        wx.hideToast()
        that.hideMenu()
        console.log('download success');
        console.log(res.tempFilePath)
        that.createNewImg(res.tempFilePath)
      }
    })
    
  }
})
